package main

import (
	"flag"
	"fmt"

	"github.com/deepin-cve/tracker/pkg/db"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
)

var (
	cveDBFile = flag.String("cve", "", "the cve db file")

	dbConn *gorm.DB
)

func main() {
	flag.Parse()

	if len(*cveDBFile) == 0 {
		flag.Usage()
		return
	}

	var err error
	dbConn, err = gorm.Open("sqlite3", *cveDBFile)
	if err != nil {
		fmt.Println("Failed to open cve db file:", err)
		return
	}
	defer dbConn.Close()

	dbConn.AutoMigrate(&db.CVE{})

	var (
		offset = 0
		limit  = 100
		length = 100
	)
	for length == limit {
		var scoreList db.CVEScoreList
		err := dbConn.Offset(offset).Limit(limit).Find(&scoreList).Error
		if err != nil {
			fmt.Println("Failed to find:", err)
			return
		}

		length = len(scoreList)
		offset += length

		var tx = dbConn.Begin().Model(&db.CVE{})
		for _, info := range scoreList {
			err := tx.Where("`id` = ?", info.ID).Updates(map[string]interface{}{
				"cvss":  "3.0",
				"score": info.Score,
			}).Error
			if err != nil {
				tx.Rollback()
				return
			}
		}
		tx.Commit()
	}
}
